import Tab from "../../components/Tab";
import Header from "../../components/Header";
import './index.scss'
import {Tabs} from "antd-mobile";
import ArticleList from "../../components/ArticleList";
import {useEffect, useState, useTransition} from "react";
import {articleList, dictArticleList} from "../../api/api";
import RequestLoading from "../../components/RequestLoading";

const Article = () => {
    const [loading, sartTransition] = useTransition();
    const [tabs, setTabs] = useState<Array<{ key: string, title: string }>>([]);
    // 选择key
    const [activeKey, setActiveKey] = useState<string>('');
    // 请求数据
    const [data, setData] = useState<Array<{ id: string, name: string, cover_url: string }>>([]);
    // 字典
    const getDict = () => {
        dictArticleList().then(r => {
            let tabs = r.map((v: { id: string, name: string }, index: number) => {
                if (index === 0) {
                    setActiveKey(v.id)
                }
                return {
                    key: v.id,
                    title: v.name
                }
            });
            setTabs(tabs);
        })
    }
    //文章列表
    const geData = () => {
        articleList(activeKey).then(r => {
            const data = r.map((v: { id: string, name: string, cover: { path: string } }) => {
                return {
                    ...v,
                    cover_url: v.cover.path
                }
            });
            setData(data);
        })
    }

    useEffect(() => {
        getDict();
    }, [])

    useEffect(() => {
        if (activeKey) {
            geData()
        }
    }, [activeKey])
    return (
        <div className="article-box">
            <Header back={null} title="文章"/>
            <div>
                <Tabs activeKey={activeKey} onChange={(v: string) => setActiveKey(v)}>
                    {
                        tabs.map(v => {
                            return (
                                <Tabs.Tab title={v.title} key={v.key}>
                                    {
                                        loading ? <RequestLoading/> : (
                                            <ArticleList data={data}/>
                                        )
                                    }
                                </Tabs.Tab>
                            )
                        })
                    }
                </Tabs>
            </div>
            <Tab/>
        </div>
    )
}

export default Article;